package net.k3rnel.abugadro;

import com.flurry.android.FlurryAgent;

import net.k3rnel.abugadro.Project.Projects;
import net.k3rnel.abugadro.gcodes.GoogleCodeHome;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Abugadro extends ListActivity implements AsyncQueryListener{

	public static final  String ABUGADRO_PREFS = "abugadro.prefs";
	private ProjectsAdapter mAdapter;
	private NotifyingAsyncQueryHandler mHandler;
	private SharedPreferences prefsPrivate;

	@Override
	public void onStart()
	{
		super.onStart();
		prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
		if(prefsPrivate.getBoolean("Flurry",false))  //Never get data without asking the user. 
			startFlurry();
	}
	@Override
	public void onStop()
	{
		super.onStop();
		prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
		if(prefsPrivate.getBoolean("Flurry",false))  //Never get data without asking the user. 
			stopFlurry();
	}
	private void startFlurry() {
		FlurryAgent.onStartSession(this, this.getString(R.string.flurry));
		FlurryAgent.onPageView();
	}
	private void stopFlurry(){
		FlurryAgent.onEndSession(this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_projects);
		((TextView) findViewById(R.id.title_text)).setText(getTitle());

		mAdapter = new ProjectsAdapter(this);
		setListAdapter(mAdapter);

		final Uri projectUri = Projects.CONTENT_URI;

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		mHandler.startQuery(projectUri, ProjectsQuery.PROJECTION, Projects.DEFAULT_SORT);
		prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
		if(prefsPrivate.getBoolean("Flurry-first",true)){ //It's true for first-run
			//Display annoying popup
			AlertDialog ad = new AlertDialog.Builder(this)
			.setTitle("Hey there!")
			.setMessage("Thanks for using Abugadro. \nWould you mind sending anonymous usage data? \nIt'll really help improve the app.")
			.setPositiveButton("Sure", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					//Save preferences
					prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
					Editor prefsPrivateEditor = prefsPrivate.edit();
					prefsPrivateEditor.putBoolean("Flurry-first",false);
					prefsPrivateEditor.putBoolean("Flurry",true);
					prefsPrivateEditor.commit();
					Toast.makeText(getApplicationContext(), "Thanks! \nIf you change your mind, hit Menu-> Settings and select Send Data", Toast.LENGTH_SHORT).show();
					startFlurry();
				}
			})
			.setNegativeButton("Nah", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					//Save preferences
					prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
					Editor prefsPrivateEditor = prefsPrivate.edit();
					prefsPrivateEditor.putBoolean("Flurry-first",false);
					prefsPrivateEditor.putBoolean("Flurry",false);
					prefsPrivateEditor.commit();
					Toast.makeText(getApplicationContext(), "If you change your mind, hit Menu-> Settings and select Send Data", Toast.LENGTH_SHORT).show();

				}
			})
			.setNeutralButton("Wait, what?", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					showMoreInfo();
				}
			})			
			.create();
			ad.show();
			if(prefsPrivate.getBoolean("Abugadro-first",true)){ //It's true for first-run
				Toast.makeText(getApplicationContext(), "You can add projects by clicking the + button on the top.", Toast.LENGTH_LONG).show();
				prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
				Editor prefsPrivateEditor = prefsPrivate.edit();
				prefsPrivateEditor.putBoolean("Abugadro-first",false);
				prefsPrivateEditor.commit();
			}
		}
	}
	private void showMoreInfo() {
		AlertDialog ad = new AlertDialog.Builder(this)
		.setTitle("About Data Collection")
		.setMessage("Abugadro uses Flurry to collect data. \nIt's totally optional and anonymous.\nIt sends phone model, as well as application usage.\nIt'll never send passwords, emails or phone numbers.")
		.setPositiveButton("Alright", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				//Save preferences
				prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
				Editor prefsPrivateEditor = prefsPrivate.edit();
				prefsPrivateEditor.putBoolean("Flurry-first",false);
				prefsPrivateEditor.putBoolean("Flurry",true);
				prefsPrivateEditor.commit();
				Toast.makeText(getApplicationContext(), "Thanks! \nIf you change your mind, hit Menu-> Settings and select Send Data", Toast.LENGTH_SHORT).show();
				startFlurry();
			}
		})
		.setNegativeButton("I'd rather not", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				//Save preferences
				prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
				Editor prefsPrivateEditor = prefsPrivate.edit();
				prefsPrivateEditor.putBoolean("Flurry-first",false);
				prefsPrivateEditor.putBoolean("Flurry",false);
				prefsPrivateEditor.commit();
				Toast.makeText(getApplicationContext(), "If you change your mind, hit Menu-> Settings and select Send Data", Toast.LENGTH_SHORT).show();

			}
		})
		.setNeutralButton("About Flurry", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				String url = "http://www.flurry.com/about-us/legal.html";
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setData(Uri.parse(url));
				startActivity(i);
			}
		})
		.create();
		ad.show();

	}
	/** {@inheritDoc} */
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		startManagingCursor(cursor);
		mAdapter.changeCursor(cursor);
	}

	/** Handle "search" title-bar action. */
	public void onSearchClick(View v) {
		//		UIUtils.goSearch(this);
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Okay", null)
		.setTitle("Sorry Dude!")
		.setMessage("Search function isn't ready!")
		.create();
		ad.show();
	}

	/** Handle "add" title-bar action. */
	public void onAddClick(View v) {
		startActivityForResult(new Intent(Abugadro.this, ProjectEditor.class), 1);
	}

	/** {@inheritDoc} */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		if (id >= 0) {
			int type = ProjectsDB.getInstance().getProjectTypeById(getContentResolver(),id);
			switch(type){
			case 0:
				final Uri projectURI = Uri.parse("content://"+ AbugadroContentProvider.AUTHORITY + "/projects/"+id+"/gcode");
				Intent i = new Intent(getApplicationContext(),GoogleCodeHome.class);
				i.setAction(android.content.Intent.ACTION_VIEW);
				i.setDataAndType(projectURI,"vnd.android.cursor.dir/*");
				startActivity(i);
				break;
			}
		}
	}

	/**
	 * {@link ProjectsAdapter} that renders a {@link ProjectQuery}.
	 */
	private class ProjectsAdapter extends CursorAdapter {
		private LayoutInflater mInflater;

		public ProjectsAdapter(Context context) {
			super(context, null);
			mInflater = LayoutInflater.from(context);
		}

		/** {@inheritDoc} */
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			return getLayoutInflater().inflate(R.layout.list_item_project, parent, false);
		}

		/** {@inheritDoc} */
		@Override
		public void bindView(View view, Context context, Cursor cursor) {

			int projType = cursor.getInt(ProjectsQuery.TYPE);
			Bitmap projectIcon;
			switch(projType){
			case 0:
				projectIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.gcode);
				break;
			case 1:
				projectIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.launchpad);
				break;
			default:
				projectIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
				break;
			}

			((ImageView)view.findViewById(R.id.project_icon)).setImageBitmap(projectIcon);

			((TextView)view.findViewById(R.id.project_name)).setText(cursor
					.getString(ProjectsQuery.NAME));   
			((ImageView)view.findViewById(R.id.project_edit_icon)).setTag(cursor
					.getInt(ProjectsQuery.ID));
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if(convertView==null)
				convertView = mInflater.inflate(R.layout.list_item_project, null);
			((ImageView)convertView.findViewById(R.id.project_edit_icon)).setTag(position);

			((ImageView)convertView.findViewById(R.id.project_edit_icon)).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					final Uri projectURI = Uri.parse("content://"+ AbugadroContentProvider.AUTHORITY + "/projects/"+view.getTag().toString().trim());
					Intent i = new Intent(getApplicationContext(),ProjectEditor.class);
					i.setAction(android.content.Intent.ACTION_EDIT);
					i.setData(projectURI);
					startActivity(i);

				}
			});
			return super.getView(position, convertView, parent);
		}

	}

	/** {@link Projects} query parameters. */
	private interface ProjectsQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Projects.NAME,
				Projects.TYPE,
		};
		int ID = 0;
		int NAME = 1;
		int TYPE = 2;
	}
}